﻿using System;
using UnityEngine;

namespace Mars.GpuInstance
{
    public class TestGpuInstanceLoader : MonoBehaviour
    {
        public string testPath;

        public Camera drawCamera;
        public int count = 100;
        public int interval = 2;
        public float speed = 1f;

        private void Awake()
        {
            if (drawCamera == null)
            {
                drawCamera = Camera.main;
            }
        }

        private void OnEnable()
        {
            AddInstance();
        }

        private void Update()
        {
            if (drawCamera)
            {
                var cameraTransform = drawCamera.transform;
                if (Input.GetKey(KeyCode.A))
                {
                    cameraTransform.position -= cameraTransform.right * speed;
                }

                if (Input.GetKey(KeyCode.D))
                {
                    cameraTransform.position += cameraTransform.right * speed;
                }

                if (Input.GetKey(KeyCode.W))
                {
                    cameraTransform.position += new Vector3(0, 0, 1) * speed;
                }

                if (Input.GetKey(KeyCode.S))
                {
                    cameraTransform.position -= new Vector3(0, 0, 1) * speed;
                }

                if (Input.GetKeyUp(KeyCode.C))
                {
                    InstanceProceduralManager.GetInstance().ClearInstance(testPath);
                }

                if (Input.GetKeyUp(KeyCode.V))
                {
                    AddInstance();
                }
            }
        }


        private void AddInstance()
        {
            var instanceProceduralManager = InstanceProceduralManager.GetInstance();
            var cameraPos = drawCamera.transform.position;
            for (var i = 0; i < count; i++)
            {
                var r = Quaternion.Euler(Vector3.zero);
                var s = new Vector3(1, 1, 1);

                instanceProceduralManager.AddInstance(testPath, GetPosition(i, cameraPos.y - 10));
            }
        }

        private Vector3 GetPosition(int index, float y)
        {
            int col = index % 100;
            int row = index / 100;

            return new Vector3(col * interval, y, row * interval);
        }
    }
}